*** Settings ***
Library           RequestsLibrary
Library           Collections

Documentation     API自动化测试示例 - JSONPlaceholder API
Suite Setup       Create Session    jsonplaceholder    https://jsonplaceholder.typicode.com
Suite Teardown    Delete All Sessions


*** Variables ***
${BASE_URL}       https://jsonplaceholder.typicode.com


*** Test Cases ***
测试01-获取所有文章列表
    [Documentation]    验证获取所有文章接口
    [Tags]    smoke    api
    ${response}=    GET On Session    jsonplaceholder    /posts

    Status Should Be    200    ${response}
    ${posts}=    Set Variable    ${response.json()}
    Length Should Be    ${posts}    100
    Log    成功获取 ${posts.__len__()} 篇文章


测试02-获取单篇文章
    [Documentation]    验证获取指定ID文章
    [Tags]    api
    ${response}=    GET On Session    jsonplaceholder    /posts/1

    Status Should Be    200
    ${post}=    Set Variable    ${response.json()}
    Should Be Equal As Integers    ${post}[id]    1
    Dictionary Should Contain Key    ${post}    title
    Dictionary Should Contain Key    ${post}    body

    Log    文章标题: ${post}[title]


测试03-创建新文章
    [Documentation]    验证创建文章接口
    [Tags]    api
    ${headers}=    Create Dictionary    Content-Type=application/json
    ${data}=    Create Dictionary    title=Robot Framework测试    body=通过Jenkins执行的RF自动化测试    userId=1

    ${response}=    POST On Session    jsonplaceholder    /posts    json=${data}    headers=${headers}

    Status Should Be    201
    ${created}=    Set Variable    ${response.json()}
    Should Be Equal    ${created}[title]    Robot Framework测试

    Log    创建成功，ID: ${created}[id]


测试04-更新文章
    [Documentation]    验证更新文章接口
    [Tags]    api
    ${headers}=    Create Dictionary    Content-Type=application/json
    ${data}=    Create Dictionary    id=1    title=更新后的标题    body=更新后的内容    userId=1

    ${response}=    PUT On Session    jsonplaceholder    /posts/1    json=${data}    headers=${headers}

    Status Should Be    200
    ${updated}=    Set Variable    ${response.json()}
    Should Be Equal    ${updated}[title]    更新后的标题


测试05-删除文章
    [Documentation]    验证删除文章接口
    [Tags]    api
    ${response}=    DELETE On Session    jsonplaceholder    /posts/1

    Status Should Be    200
    Log    删除成功


测试06-响应时间验证
    [Documentation]    验证API响应时间在可接受范围内
    [Tags]    performance
    ${response}=    GET On Session    jsonplaceholder    /posts

    Status Should Be    200
    ${elapsed_ms}=    Evaluate    ${response.elapsed.total_seconds()} * 1000
    Should Be True    ${elapsed_ms} < 3000    响应时间过长: ${elapsed_ms}ms

    Log    响应时间: ${elapsed_ms}ms


测试07-错误处理-不存在的资源
    [Documentation]    验证获取不存在资源的处理
    [Tags]    negative
    ${response}=    GET On Session    jsonplaceholder    /posts/99999    expected_status=any

    # JSONPlaceholder对不存在的资源返回200和空对象（不是404）
    Status Should Be    200
    ${data}=    Set Variable    ${response.json()}
    # 验证返回的是空对象
    Run Keyword And Ignore Error    Should Be Empty    ${data}


*** Keywords ***
# 自定义关键字可以在这里定义
